package com.million.base;

import com.million.base.enums.EvictionType;
import com.million.service.EvictionStrategy;
import com.million.service.impl.MiraiImpl;
import com.million.service.impl.ShizukaImpl;
import com.million.service.impl.TsubasaImpl;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author miki
 * @Date 2022/1/22 0:43
 * @Explain loop 处理，减少类的改动，尽量契合开闭原则
 * 好处：减少代码改动的类，这里只需要在初始化的时候加一条，如果按照从类中加载可以完全不用
 */
public class EvictionStrategyLoopFactory {

    private static final List<EvictionRange> evictionList = new ArrayList<>(6);

    static {
        evictionList.add(new EvictionRange(EvictionType.MIRAI, MiraiImpl.class));
        evictionList.add(new EvictionRange(EvictionType.SHIZUKA, ShizukaImpl.class));
        evictionList.add(new EvictionRange(EvictionType.TSUBASA, TsubasaImpl.class));
    }


    public static EvictionStrategy clientSelect(String eviction) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        EvictionStrategy evictionStrategy = null;
        for (EvictionRange evictionRange : evictionList){
            if (evictionRange.select(eviction)){
                Class<EvictionStrategy> evictionStrategyClass = evictionRange.getEvictionStrategyClass();
                Constructor constructor = evictionStrategyClass.getConstructor();
                evictionStrategy = (EvictionStrategy) constructor.newInstance();
                break;
            }
        }
        return evictionStrategy;
    }
}
